package com.kaibes.im.control.service;

import java.io.IOException;
import java.net.Socket;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.kaibes.im.KaibesApplication;
import com.kaibes.im.control.thread.ConnectThread;

public class KaibesService extends Service {

    private ConnectThread connect = null;

    @Override
    public void onCreate() {
	super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
	return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
	if (connect != null) {
	    closeClient();
	    connect = null;
	}
	connect = new ConnectThread((KaibesApplication) getApplication(), this);
	connect.start();
	return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
	closeClient();
	super.onDestroy();
	
	if (((KaibesApplication) getApplication()).getCurrentActivity() != null) {
	    ((KaibesApplication) getApplication()).getCurrentActivity()
		    .finish();
	}
	android.os.Process.killProcess(android.os.Process.myPid());
    }

    private void closeClient() {
	try {
	    Socket client = connect.getClient();
	    if (client != null && !client.isClosed()) {
		client.close();
	    }
	} catch (IOException e) {
	    e.printStackTrace();
	}
    }

}
